package com.yx.enterresourceplanning.controller;

import com.aliyun.ocr_api20210707.models.RecognizeGeneralRequest;
import com.aliyun.ocr_api20210707.models.RecognizeGeneralResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.aliyun.ocr_api20210707.Client;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Base64;

@RestController
@RequestMapping("/ocr")
public class OcrController {
    // 阿里云OCR配置
    private Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId("LTAI5t7V9j3ekSdy7YfbBmTx")
                .setAccessKeySecret("4Dv98agRUnUQWPMtG08hPU3NuAHYGB");
        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new Client(config);
    }
    @PostMapping("/recognize")
    public String recognize(@RequestParam("file") MultipartFile file) {
        try {
            // 读取文件并转为Base64
            byte[] fileBytes = file.getBytes();

            // 调用阿里云OCR
            Client client = createClient();
            RecognizeGeneralRequest request = new RecognizeGeneralRequest();
            
            // 直接传递原始图像数据
            request.setBody(new ByteArrayInputStream(fileBytes));
            
            RecognizeGeneralResponse response = client.recognizeGeneral(request);

            // 返回识别结果
            return response.getBody().getData();
        } catch (Exception e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }
}
